package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.OrderConstant;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.common.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.constant.OrderStatusEnum;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.OrderInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    PaymentInfoService paymentInfoService;
    @Autowired
    RabbitTemplate rabbitTemplate;


    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils listWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = OrderInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> collect = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> entities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(entities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(collect);
        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo vo = new OrderConfirmVo();
        MemberRespVo memberRespVo = OrderInterceptor.threadLocal.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> addressTask = CompletableFuture.runAsync(() -> {
            //多线程丢失请求头，使用主线程的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询收货地址
            vo.setAddresses(memberFeignService.getAddresses(memberRespVo.getId()));
        }, executor);
        CompletableFuture<Void> cartTask = CompletableFuture.runAsync(() -> {
            //多线程丢失请求头，使用主线程的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询购物车所有购物项
            vo.setItems(cartFeignService.getCurrentUserCartItems());
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = vo.getItems();
            List<Long> ids = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wareFeignService.getSkusHasStock(ids);
            List<SkuHasStockVo> data = (List<SkuHasStockVo>) r.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
            vo.setStocks(map);
        });
        //查询用户积分
        vo.setIntegration(memberRespVo.getIntegration());
        //防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        vo.setOrderToken(token);

        try {
            CompletableFuture.allOf(addressTask, cartTask).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return vo;
    }

    //@GlobalTransactional
    @Transactional
    @Override
    public OrderSubmitRespVo submitOrder(OrderSubmitVo vo) {
        confirmVoThreadLocal.set(vo);
        OrderSubmitRespVo respVo = new OrderSubmitRespVo();
        respVo.setCode(0);
        //验证令牌
        MemberRespVo memberRespVo = OrderInterceptor.threadLocal.get();
        String key = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(key), vo.getOrderToken());
        if (result == 0) {//令牌验证失败
            respVo.setCode(1);
            return respVo;
        }
        OrderCreateTo order = createOrder();
        respVo.setOrder(order.getOrder());
        //验价
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal payPrice = vo.getPayPrice();
        if(Math.abs(payAmount.subtract(payPrice).doubleValue())>=0.01){
            respVo.setCode(2);
            return respVo;
        }
        //保存订单
        save(order.getOrder());
        orderItemService.saveBatch(order.getOrderItems());
        //锁定库存
        WareSkuLockVo lockVo=new WareSkuLockVo();
        lockVo.setOrderSn(order.getOrder().getOrderSn());
        List<OrderItemVo> collect = order.getOrderItems().stream().map(item -> {
            OrderItemVo itemVo = new OrderItemVo();
            itemVo.setSkuId(item.getSkuId());
            itemVo.setTitle(item.getSkuName());
            itemVo.setCount(item.getSkuQuantity());
            return itemVo;
        }).collect(Collectors.toList());
        lockVo.setLocks(collect);
        R r = wareFeignService.orderLockStock(lockVo);
        if(r.getCode()!=0){
            throw new NoStockException(1L);
        }
        //int i=1/0;
        //发送消息：订单创建成功
        rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
        return respVo;
    }

    private OrderCreateTo createOrder() {
        MemberRespVo memberRespVo = OrderInterceptor.threadLocal.get();
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        OrderCreateTo createTo = new OrderCreateTo();
        String orderSn = IdWorker.getTimeId();
        //订单
        OrderEntity order = new OrderEntity();
        createTo.setOrder(order);
        order.setOrderSn(orderSn);
        order.setDeleteStatus(0);
        order.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        order.setMemberId(memberRespVo.getId());

        R r = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = (FareVo) r.getData(new TypeReference<FareVo>() {
        });
        order.setFreightAmount(fareVo.getFare());

        order.setReceiverCity(fareVo.getAddress().getCity());
        order.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        order.setReceiverName(fareVo.getAddress().getName());
        order.setReceiverPhone(fareVo.getAddress().getPhone());
        order.setReceiverPostCode(fareVo.getAddress().getPostCode());
        order.setReceiverProvince(fareVo.getAddress().getProvince());
        order.setReceiverRegion(fareVo.getAddress().getRegion());
        //订单项
        List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
        if (cartItems != null && cartItems.size() > 0) {
            List<OrderItemEntity> collect = cartItems.stream().map(item -> {
                OrderItemEntity entity = new OrderItemEntity();
                entity.setOrderSn(orderSn);
                entity.setSkuId(item.getSkuId());
                entity.setSkuName(item.getTitle());
                entity.setSkuPrice(item.getPrice());
                entity.setSkuPic(item.getImage());
                String skuAttr = StringUtils.collectionToDelimitedString(item.getSkuAttr(), ";");
                entity.setSkuAttrsVals(skuAttr);
                entity.setSkuQuantity(item.getCount());

                entity.setGiftGrowth(item.getPrice().intValue()*item.getCount());
                entity.setGiftIntegration(item.getPrice().intValue()*item.getCount());

                R pr = productFeignService.getSpuBySkuId(item.getSkuId());
                SpuInfoVo spuInfoVo = (SpuInfoVo) pr.getData(new TypeReference<SpuInfoVo>() {
                });
                entity.setSpuId(spuInfoVo.getId());
                entity.setSpuBrand(spuInfoVo.getBrandId().toString());
                entity.setSpuName(spuInfoVo.getSpuName());
                entity.setCategoryId(spuInfoVo.getCatalogId());

                entity.setPromotionAmount(new BigDecimal(0));
                entity.setCouponAmount(new BigDecimal(0));
                entity.setIntegrationAmount(new BigDecimal(0));
                //应该再减去上述三个优惠金额，因为优惠都是0，就不写了
                entity.setRealAmount(entity.getSkuPrice().multiply(new BigDecimal(entity.getSkuQuantity())));

                return entity;
            }).collect(Collectors.toList());
            createTo.setOrderItems(collect);
        }
        //验价
        BigDecimal total=new BigDecimal(0);
        Integer gift=0;
        Integer growth=0;
        List<OrderItemEntity> orderItems = createTo.getOrderItems();
        for (OrderItemEntity item : orderItems) {
            BigDecimal realAmount = item.getRealAmount();
            total=total.add(realAmount);
            gift+=item.getGiftIntegration();
            growth+=item.getGiftGrowth();
        }
        order.setTotalAmount(total);
        order.setPayAmount(total.add(order.getFreightAmount()));
        order.setPromotionAmount(new BigDecimal(0));//三个优惠金额和
        order.setCouponAmount(new BigDecimal(0));
        order.setAutoConfirmDay(7);
        order.setIntegration(gift);
        order.setGrowth(growth);

        return createTo;
    }

    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的最新状态
        OrderEntity orderEntity = getById(entity.getId());
        if(orderEntity.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
            //创建一个新对象，以免更新影响已经变化的数据
            OrderEntity updateEntity =new OrderEntity();
            updateEntity.setId(entity.getId());
            updateEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            updateById(updateEntity);
            //发送消息：给库存解锁队列发送消息，
            //防止订单服务卡顿，导致库存解锁消息优先到期，而订单未关单，导致库存无法解锁
            OrderTo to=new OrderTo();
            BeanUtils.copyProperties(entity,to);
            //保证消息一定会发出去，每一个消息存入mq_message表中，定期扫描数据，重新发送
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",to);
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn){
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    @Override
    public PayVo getPayVo(String orderSn) {
        OrderEntity order = getOrderByOrderSn(orderSn);
        List<OrderItemEntity> items = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity=items.get(0);
        PayVo vo = new PayVo();
        vo.setBody(entity.getSkuAttrsVals());
        vo.setOut_trade_no(orderSn);
        vo.setSubject(entity.getSkuName());
        vo.setTotal_amount(order.getPayAmount().setScale(2,BigDecimal.ROUND_UP).toString());
        return vo;
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //保存交易流水
        PaymentInfoEntity infoEntity=new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);
        //修改订单信息
        if(vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")){
            updateOrderStatus(infoEntity.getOrderSn(),OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    private void updateOrderStatus(String orderSn, int code) {
        baseMapper.updateOrderStatus(orderSn,code);
    }

    @Transactional
    @Override
    public void handleOrderSeckill(SeckillOrderTo entity) {
        //保存订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(entity.getOrderSn());
        orderEntity.setMemberId(entity.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal payAmount = entity.getSeckillPrice().multiply(new BigDecimal(entity.getNum()));
        orderEntity.setPayAmount(payAmount);
        save(orderEntity);
        //保存订单项
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(entity.getOrderSn());
        itemEntity.setRealAmount(payAmount);
        itemEntity.setSkuQuantity(entity.getNum());
        orderItemService.save(itemEntity);
    }
}
